package com.huluobo.a2203kotlinshopping.cart

import android.content.Intent
import android.util.Log
import android.widget.CheckBox
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.a2203kotlinshopping.R
import com.huluobo.a2203kotlinshopping.adapter.CartAdapter
import com.huluobo.a2203kotlinshopping.databinding.FragmentCartBinding
import com.huluobo.a2203kotlinshopping.order.PayActivity
import com.huluobo.base.bean.CartBean
import com.huluobo.base.bean.OrderBean
import com.huluobo.base.db.AppDBUtils
import com.huluobo.base.view.BaseMVVMFragment

class CartFragment : BaseMVVMFragment<FragmentCartBinding, CartViewModel>() {

    private lateinit var cartAdapter: CartAdapter
    private val cartList = mutableListOf<CartBean>()

    override fun getLayoutId(): Int = R.layout.fragment_cart

    override fun getViewModel(): Class<CartViewModel> = CartViewModel::class.java

    override fun initData() {
        viewModel.queryCart()

        viewModel.queryCartSuccess.observe(this) {
            if (it.code == 200) {
                cartList.clear()
                cartList.addAll(it.data)
                cartAdapter.notifyDataSetChanged()
            } else {
                ToastUtils.showLong(it.message)
            }
        }

        viewModel.queryCartFaield.observe(this) {
            Log.i("TagA", "查询购物车失败 :$it")
        }

        viewModel.deleteCartSuccess.observe(this) {
            ToastUtils.showLong(it.message)
        }

        viewModel.deleteCartFailed.observe(this) {
            Log.i("TagA", "删除购物车失败:$it")
        }

        viewModel.changeCartSuccess.observe(this) {
            if (it.code == 200) {
                Log.i("TagA", "修改购物车数量成功")
            } else {
                ToastUtils.showLong("修改购物车数量失败:${it.message}")
            }
        }
        viewModel.changeCartFailed.observe(this) {
            Log.i("TagA", "修改购物车数量失败:$it")
        }
    }

    override fun initView() {
        dataBinding.cartRv.layoutManager = LinearLayoutManager(requireContext())
        cartAdapter = CartAdapter(cartList)
        dataBinding.cartRv.adapter = cartAdapter

        totalPrice()

        cartAdapter.addChildClickViewIds(
            R.id.item_cart_cb,
            R.id.item_cart_delete_iv,
            R.id.item_cart_add_iv,
            R.id.item_cart_reduce_iv
        )

        cartAdapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.item_cart_cb -> {
                    cartList[position].isChecked = !cartList[position].isChecked
                    //单独刷新一个view
                    (adapter.getViewByPosition(position, R.id.item_cart_cb) as CheckBox).isChecked =
                        cartList[position].isChecked
                }

                R.id.item_cart_delete_iv -> {
                    val ids = cartList[position].id.toString()
                    viewModel.deleteCart(ids)
                    //数据层面也要删除掉item,否则数据源中没有发生改变,adapter刷新毫无意义
                    cartList.removeAt(position)
                    //单独删除某一个item,自带动画
                    adapter.notifyItemRemoved(position)
                }

                R.id.item_cart_add_iv -> {
                    cartList[position].count += 1
                    viewModel.changeCartCount(1, cartList[position].goods_id)
                    (adapter.getViewByPosition(position, R.id.item_cart_num_tv) as TextView).text =
                        "${cartList[position].count}"
                }

                R.id.item_cart_reduce_iv -> {
                    if (cartList[position].count > 1) {
                        cartList[position].count -= 1
                        viewModel.changeCartCount(-1, cartList[position].goods_id)
                        (adapter.getViewByPosition(position, R.id.item_cart_num_tv) as TextView).text =
                            "${cartList[position].count}"
                    }
                }
            }

            //无论点击了item中哪一个按钮,都需要重新计算一下总价,包括选中,删除,修改数量
            totalPrice()
            checkAll()
        }

        //全选按钮的点击事件
        dataBinding.cartSelectAllCb.setOnCheckedChangeListener { buttonView, isChecked ->
            dataBinding.cartSelectAllCb.setOnClickListener {
                cartList.forEach {
                    //遍历购物车数据源中所有的选中项都设置为全选按钮的是否选中
                    it.isChecked = isChecked
                }
                cartAdapter.notifyDataSetChanged()
                totalPrice()
            }
        }

        //购买按钮点击事件
        dataBinding.cartPayBtn.setOnClickListener {
            val checkList = mutableListOf<Boolean>()
            cartList.forEach {
                //将购物车中所有的是否选中放到一个集合中
                checkList.add(it.isChecked)
            }
            AppDBUtils.getDb().orderDao().deleteAllOrderInfo()
            if (true in checkList) {
                cartList.forEach {
                    if (it.isChecked) {
                        val orderBean = OrderBean(
                            it.count,
                            it.goods_default_price,
                            it.goods_desc,
                            it.goods_id,
                            it.id
                        )
                        AppDBUtils.getDb().orderDao().insertOrderInfo(orderBean)
                    }
                }


                //跳转到支付页面
                val intent = Intent(requireContext(), PayActivity::class.java)
                startActivity(intent)
            } else {
                ToastUtils.showLong("请选择一个商品再进行支付")
            }
        }
    }

    override fun onResume() {
        super.onResume()
        viewModel.queryCart()
    }

    //计算总价
    private fun totalPrice() {
        var totalPrice = 0

        cartList.forEach {
            if (it.isChecked) {
                totalPrice += it.goods_default_price * it.count
            }
        }

        dataBinding.cartTotalPriceTv.text = "总价:￥$totalPrice"
    }

    private fun checkAll() {
        val checkList = mutableListOf<Boolean>()
        cartList.forEach {
            //将购物车中所有的是否选中放到一个集合中
            checkList.add(it.isChecked)
        }
        dataBinding.cartSelectAllCb.isChecked = false !in checkList
    }
}